/**
 * Created by cxl on 2017/7/18.
 */

var roomManager = require('../../../logic/world/roomManager');

module.exports = function (app) {
    return new Handler(app);
};

var Handler = function (app) {
    this.app = app;
};

var handler = Handler.prototype;

handler.agreeJoin = function (msg, session, next) {
    var gid = session.uid;
    var uid = msg.uid;

    var player = null;

    async.series([
        function (cb) {
            gGroupManager.agreeJoin(gid, uid, function (err, p) {
                if (err) {
                    cb(err);
                    return;
                }
                if (!p) {
                    cb(Code.DB_ERROR)
                    return;
                }
                player = p;
            });
            cb();
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }

        next(null, {"groups": player.user.groups});
    });
};

handler.applyJoinGroup = function (msg, session, next) {
    var gid = msg.gid;
    var uid = session.uid;

    gGroupManager.applyJoinGroup(gid, uid, function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next(null, {"statusOfApply": true})
    });
};

handler.getApplyJoinGroup = function (msg, session, next) {
    var gid = session.uid;//要查询的ID就是组ID

    gGroupManager.getApplyJoinGroup(gid, function (err, info) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next(null, {"applyInfo": info});
    });
};

/***
 * 删除指定群组中的指定会员
 * @param msg
 * @param session
 * @param next
 */
handler.delMemberOfGroup = function (msg, session, next) {
    var gid = msg.gid;
    var uid = msg.uid;
    async.series([
        function (cb) {
            gGroupManager.delMemberOfGroup(gid, uid, function (err) {
                if (err) {
                    cb(err);
                }
            });
        }
    ], function (err) {
        if (err) {
            next(err, {code: err});
            return;
        }
        next();
    });
};

handler.delApply = function (msg, session, next) {
    var gid = session.uid;
    var uid = msg.uid;

    gGroupManager.delApply(gid, uid, function (err, info) {
        next(null, info);
    });
};
